﻿#pragma once
#include <QAudioSink>
#include <QAudioSource>
#include <QFile>
#include <QMediaDevices>
#include <QObject>
#include <QStandardPaths>
///////////////////////////////////////////
/// 声音录制类
///////////////////////////////////////////
class SoundRecorder : public QObject
{
    Q_OBJECT
    const QString RECORD_PATH =
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) +
        "/sound/tmpRecord.pcm";
    const QString PLAY_PATH =
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) +
        "/sound/tmpPlay.pcm";
public:
    static SoundRecorder* get_instance();
private:
    static SoundRecorder* instance;
    explicit SoundRecorder(QObject* parent = nullptr);
    // 音频格式转换函数
    QByteArray convert_audio_format(const QByteArray&   inputData,
                                    const QAudioFormat& inputFormat,
                                    const QAudioFormat& outputFormat);
public:
    // 开始录制
    void start_record();
    // 停止录制
    void stop_record();
    // 开始播放
    void start_play(const QByteArray& content);
    // 停止播放
    void stop_play();
    // 当前是否正在播放
    bool is_playing();
signals:
    // 录制完毕后发送这个信号
    void sound_record_done(const QString& path);
    // 播放完毕后发送这个信号
    void sound_play_done();
private:
    QFile          soundFile;
    QAudioSource*  audioSource;
    QAudioSink*    audioSink;
    QMediaDevices* outputDevices;
    QAudioDevice   outputDevice;
    QFile          inputFile;
    bool           m_isPlaying;
};